package com.redoop.db;
import com.redoop.common.LogHelper;
import com.redoop.main.MainProc;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class DBCtrl
{
  private static SqlSessionFactory sqlSessionFactory = null;

	public boolean InitDBFactory(){
		try {
			FileInputStream fis = new FileInputStream(MainProc.gIniFile.getMybatis_path());
		      if (sqlSessionFactory == null) {
		        sqlSessionFactory = new SqlSessionFactoryBuilder().build(fis);
		      }
		} catch (IOException e) {
			LogHelper.error(e.getMessage());
			return false;
		}
		
		return true;
	}

	public void ExitDBFactory() {
	    sqlSessionFactory = null;
	  }

	public SqlSession getSQLSession()
	  {
	    return sqlSessionFactory.openSession();
	  }

	  public String getJdbcType(){
		return sqlSessionFactory.getConfiguration().getEnvironment().getId();
	  }
	  public List<String> getTableNameList(){
		List<String> list = new ArrayList<>();
		  BufferedReader br = null;
		  try {
			  FileReader fileReader = new FileReader(MainProc.gIniFile.getRead_path());
			  br = new BufferedReader(fileReader);
			  for (int i = 1; i < getCount(); i++) {
				  String readLine = br.readLine().replaceAll(" ", "");
				  list.add(readLine);
				  System.out.println(readLine);
			  }
			  } catch (Exception e) {
			  e.printStackTrace();
		  }finally {
			  try {
				  br.close();
			  } catch (IOException e) {
				  e.printStackTrace();
			  }
		  }
		  return list;
	  }

	public static long getCount() throws FileNotFoundException {
		FileReader fileReader = new FileReader(MainProc.gIniFile.getRead_path());
		BufferedReader br = new BufferedReader(fileReader);
		Stream<String> lines = br.lines();

		long count = lines.count();
		// System.out.println("一共读取到" + count + "行的数据，请验证后决定是否复制粘贴");
		return count;
	}
}
